<template>
  <div v-loading="loading"
       element-loading-text="数据正在加载..."
  >
    <el-button style="margin-bottom: 10px;" type="primary" @click="addData">新增</el-button>
      <el-button  style="margin-bottom: 10px;" :icon="Search" circle @click="dialogTableVisible = true" />
      <el-dialog v-model="dialogTableVisible" title="条件搜索">
          <div style="display: flex">
              <el-select v-model="searchObj.condition" class="m-2" placeholder="请选择" size="large">
                  <el-option
                          v-for="item in myTopNameList"
                          :key="item.prop"
                          :label="item.label"
                          :value="item.prop"
                  />
              </el-select>
              <el-input style="margin-left: 10px"  v-model="searchObj.content" placeholder="输入搜索内容" />
              <el-button style="margin-left: 10px;margin-top: auto;margin-bottom: auto"
                         :icon="Search" circle @click="mySearch" />
          </div>
      </el-dialog>
    <keep-alive>
      <el-table ref="table" stripe :data="myDataList" height="80vh" border style="width: 100%">
        <el-table-column type="index"  width="50" />
        <el-table-column v-for="(item,index) in myTopNameList" :prop="item.prop" :label="item.label">
          <template v-slot="scope">
            <div v-if="isShowList[scope.$index] && item.editable">
              <el-select v-if="item.type === 'list'"
                         v-model="scope.row[item.prop]" class="m-2" placeholder="请选择" size="large">
                <el-option
                    v-for="item in item.listData"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
              </el-select>
              <el-input v-else-if="item.type === 'password'"
                        :type="item.type"
                        show-password
                        clearable
                        size="small" v-model="scope.row[item.prop]"
                        placeholder="请输入"></el-input>
              <el-input-number v-else-if="item.type === 'number'" v-model="scope.row[item.prop]" :min="1" :max="10"/>
              <el-upload
                  v-else-if="item.type === 'images'"
                  class="avatar-uploader"
                  :headers="headerObj"
                  accept="jpg/png"
                  name="avatar"
                  :action="avatarUploadUrl"
                  :show-file-list="false"
                  :limit="1"
                  :data={id:getId(scope.row)}
                  :on-success="
                      (response, file, fileList) => {
                          return handleAvatarSuccess(response, file, fileList, scope.$index,item);
                        }
                      "
              >
                <img style="height: 120px;width: 120px;" v-if="scope.row[item.prop]"
                     :src="scope.row[item.prop]" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><plus /></el-icon>
              </el-upload>
              <el-input v-else
                        clearable
                        :autosize="{ minRows: 2, maxRows: 10}"
                        type="textarea"
                        size="small" v-model="scope.row[item.prop]"
                        placeholder="请输入"></el-input>
            </div>
            <span v-else-if="item.type === 'password'">*******</span>
            <el-image v-else-if="item.type === 'images'" style="width: 80px; height: 80px"
                      :src="scope.row[item.prop]" fit="contain" />
            <span v-else>{{  getCellContent(scope.$index,item) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" >
          <template  v-slot="scope">
            <el-button size="small" :type="editBtnType(scope.$index)" @click="editData(scope.$index)" >
              {{ editBtnText(scope.$index) }}</el-button>
            <el-popconfirm title="你确定要删除吗?"
                           confirm-button-text="确定"
                           cancel-button-text="误触误触"
                           @confirm="deleteData(scope.$index)"
            >
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </keep-alive>
    <div style="width: max-content;margin: 20px auto 30px;">
      <el-pagination background layout="prev, pager, next"
                     @current-change = "currentChange"
                     v-model:current-page="myNowPage"
                     v-model:page-count="myPages" />
    </div>
  </div>
</template>

<script setup>
import { Plus,Search } from '@element-plus/icons-vue'
import {computed, onMounted, reactive, ref, toRaw, watch} from "vue";
import { onBeforeRouteLeave, onBeforeRouteUpdate,useRoute } from 'vue-router'
import {ElMessage, ElMessageBox} from "element-plus";
import axios from "../../axios/axios.js";
import store from "../../store/store";

let loading = ref(false)

let searchObj = reactive({
    condition: "",
    content: ""
})

let dialogTableVisible = ref(false)

const route = useRoute();

const headerObj = reactive({
  Authorization: localStorage.getItem("token")
})

let avatarUploadUrl = ref("/avatar/upload")

const getId  = (row)=>{
  return row[myTopNameList.value[0].prop];
}

const handleAvatarSuccess = (res,file, fileList,index,type) => {
   myDataList.value[index][type.prop]  = res.data
}

const myProps = defineProps({
  requestUrlObj: {
    type: Object,
    default: {
      "updateUrl": "",
      "insertUrl": "",
      "deleteUrl": "",
      "readUrl": "",
      "topUrl": "",
      "searchUrl": ""
    }
  },
})

const myDataList = ref([])
const myTopNameList = ref([])
let myPages = ref(1)
let myNowPage = ref(1)
let isNowEdit = false;
let isShowList = ref([])
let idName = ""

watch(()=>myProps.requestUrlObj,(old,newValue)=>{
  //console.log("2检测到了");
  //console.log(newValue);
  if (newValue !== undefined) {
    myDataList.value = []
    myTopNameList.value= []
    getTopDataList();
    //getDataList(1);
  }
},{
  //非惰性
  immediate: true,
  //深度监视
  deep: true
})
const currentChange = (index)=>{
  //console.log(index);
  getDataList(index);
}

const getCellContent = computed(()=>(index, type)=>{
  if (type.type === "list") {
    let id = myDataList.value[index][type.prop]
    for (let i = 0; i < type.listData.length; i++) {
      if (type.listData[i].id === id) {
        //console.log(type.listData[i].id ,id);
        return type.listData[i].name;
      }
    }
  }else{
    if (myDataList.value[index][type.prop] !== null) {
      if (myDataList.value[index][type.prop].length > 20) {
        return myDataList.value[index][type.prop].substring(0,20)+ "......";
      }
    }
    return myDataList.value[index][type.prop];
  }
})

const editBtnType = computed(()=>(index)=>{
  if (isShowList.value[index]){
    return "warning"
  }else{
    return "primary"
  }
})
const editBtnText = computed(()=>(index)=>{
  if (isShowList.value[index]){
    return "保存"
  }else{
    return "编辑"
  }
})

onMounted(()=>{
  //getTopDataList();
  avatarUploadUrl.value = store.getters.getRequestUrl + "/" + route.query.query+ avatarUploadUrl.value;
})

const getTopDataList = ()=>{
  axios.get(myProps.requestUrlObj.topUrl).then(res=>{
    //console.log( "123"+res.data.data);
    myTopNameList.value = res.data.data;
    idName = myTopNameList.value[0].prop;
    getDataList(1);
  }).catch((error)=>{
    console.log(error)
    ElMessage({
      showClose: true,
      message: '查询失败,请刷新重试!',
      type: 'error',
    })
  })
}

const getDataList = (page)=>{
  if (typeof page === "undefined" || page === "" || page === null) {
    page = 1;
  }
  loading.value = true
  myDataList.value = []
  axios.get(myProps.requestUrlObj.readUrl+"/" + page).then(res=>{
    //console.log(res.data.data);
    myDataList.value = []
    isShowList.value = []
    myDataList.value = res.data.data.data;
    myPages.value = res.data.data.pages;
    myNowPage.value = res.data.data.nowPage;
    loading.value = false
  }).catch((error)=>{
    console.log(error)
    loading.value = false
    ElMessage({
      showClose: true,
      message: '查询失败,请刷新重试!',
      type: 'error',
    })
  })
}

const editData = (index)=>{
  //console.log(idName , index);
  if (isShowList.value[index]) {
    if (myDataList.value[index][idName] == null){
      axios.post(myProps.requestUrlObj.insertUrl,myDataList.value[index]).then((res)=>{
        //console.log(res.data);
        myDataList.value[index] = res.data.data;
        isShowList.value[index] = false;
        ElMessage({
          showClose: true,
          message: '添加成功!',
          type: 'success',
        })
      }).catch((error)=>{
        console.log(error)
        ElMessage({
          showClose: true,
          message: '新增未成功,请稍后再试!',
          type: 'error',
        })
      })
    }else{
      axios.post(myProps.requestUrlObj.updateUrl,myDataList.value[index]).then((res) => {
         //console.log(res.data.data)
        myDataList.value[index] = res.data.data;
        isShowList.value[index] = false;
        ElMessage({
          showClose: true,
          message: '修改成功!',
          type: 'success',
        })
      }).catch((error)=>{
        console.log(error)
        ElMessage({
          showClose: true,
          message: '更新未成功,请稍后再试!',
          type: 'error',
        })
      })
    }
  }else{
    isShowList.value[index] = true;
  }
}

onBeforeRouteLeave((to,from)=>{
  //flashNowEdit();
  if (isNowEdit === true){
    ElMessageBox.alert('你还有修改未保存,请保存后退出', '警告', {
      confirmButtonText: '好的',
      callback: () => {
        return false
      }
    })
  }
})

const addData = ()=>{
  // console.log("新增")
  if (isShowList.value[0] === true) {
    ElMessage({
      showClose: true,
      message: '请先保存以前的新增',
      type: 'warning',
    })
  }else{
    let obj = {}
    for(let item of myTopNameList.value) {
      obj[item.prop] = null
    }
    myDataList.value.unshift(obj);
    //console.log(myDataList.value[0]);
    isShowList.value.unshift(true);
  }
}

const deleteData = (index)=>{
  //console.log(index,idName)
  //console.log(myDataList.value[index][idName]);
  if (myDataList.value[index][idName] === null){
    myDataList.value.splice(index, 1)
    isShowList.value.splice(index, 1)
    //flushData();
    ElMessage({
      showClose: true,
      message: '删除未保存的新增',
      type: 'success',
    })
    // console.log(this.isShowList)
  }else{
    axios.get(myProps.requestUrlObj.deleteUrl+"/"+myDataList.value[index][idName]).then(()=>{
      // console.log(res.data.data)
      myDataList.value.splice(index, 1)
      isShowList.value.splice(index, 1)
      //flushData();
      ElMessage({
        showClose: true,
        message: '成功删除',
        type: 'success',
      })
      // console.log(this.isShowList.length)
    }).catch((error)=>{
      console.log(error)
      ElMessage({
        showClose: true,
        message: '删除未成功,请稍后再试!',
        type: 'error',
      })
    })
  }
}

let mySearch = ()=>{
    dialogTableVisible.value = false
    //console.log(searchObj);
    axios.post(myProps.requestUrlObj.searchUrl, searchObj).then((res)=>{
        //console.log(res.data.data);
        myDataList.value = []
        isShowList.value = []
        myDataList.value = res.data.data.data;
        myPages.value = res.data.data.pages;
        myNowPage.value = res.data.data.nowPage;
    }).catch((error)=>{
        console.log(error)
        ElMessage({
            showClose: true,
            message: '查询失败,请稍后再试!',
            type: 'error',
        })
    })
    searchObj.condition = ""
    searchObj.content = ""
}



</script>

<style scoped>

</style>
